/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package ULHT.LIG2N1.RC.CLIENTINTERFACE;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;

/**
 *
 * @author Administrador
 */
public class CheckConnectionThread extends Thread {

    private Socket conn;
    private boolean alive;
    private static BufferedReader in;
    private static PrintWriter out;
    private boolean running;

    public CheckConnectionThread(Socket conn, boolean alive) {
        this.running = true;
        try {
            this.conn = conn;
            this.alive = alive;
            // 3 segundos de timeout até considerar que a ligação caiu
            conn.setSoTimeout(3000);
            in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            out = new PrintWriter(conn.getOutputStream(), true);
        } catch (IOException ex) {
            this.alive = false;
        }
        while (running) {
            try {
                this.alive = heartbeat();
                this.sleep(1000);
            } catch (InterruptedException ex) {
                return;
            }
        }
    }

    public void halt() {
        this.running = false;
    }

    private boolean heartbeat() {
        int msgSize;
        String serverReply;
        char[] buffer = null;
        try {
            out.println("PING");
            do {
                serverReply = in.readLine();
                if (serverReply != null && serverReply.length() > 0) {
                    if (serverReply.isEmpty()) {
                        throw new IOException("Sevidor não enviou o tamanho");
                    } else {
                        try {
                            msgSize = Integer.parseInt(serverReply);
                        } catch (NumberFormatException nfe) {
                            throw new IOException("Tamanho no formato errado");
                        }
                        buffer = new char[msgSize];
                        int totalRead = 0;
                        while (totalRead < msgSize) {
                            int read = in.read(buffer, totalRead, msgSize - totalRead);
                            if (read == -1) {
                                throw new IOException("Dados insuficientes");
                            }
                            totalRead += read;
                        }
                    }
                }
            } while (serverReply == null || serverReply.length() <= 0);

            if (new String(buffer).equalsIgnoreCase("PONG")) {
                return true;
            } else {
                return false;
            }
        } catch (IOException ex) {
            return false;
        }
    }

    private void writeToServer(String output) {
        if (!conn.isClosed()) {
            out.println(output);
        }
    }

    private String readFromServerEvo() throws IOException {
        int msgSize;
        String serverReply;
        char[] buffer = null;
        do {
            serverReply = in.readLine();
            if (serverReply != null && serverReply.length() > 0) {
                if (serverReply.isEmpty()) {
                    throw new IOException("Sevidor não enviou o tamanho");
                } else {
                    try {
                        msgSize = Integer.parseInt(serverReply);
                    } catch (NumberFormatException nfe) {
                        throw new IOException("Tamanho no formato errado");
                    }
                    buffer = new char[msgSize];
                    int totalRead = 0;
                    while (totalRead < msgSize) {
                        int read = in.read(buffer, totalRead, msgSize - totalRead);
                        if (read == -1) {
                            throw new IOException("Dados insuficientes");
                        }
                        totalRead += read;
                    }
                }
            }
        } while (serverReply == null || serverReply.length() <= 0);

        return new String(buffer);
    }
}
